package cmd

import (
	"fmt"
	"io/ioutil"
	"net"

	"gitee.com/shaddy/k3sinstall/install"
	"gitee.com/shaddy/k3sinstall/mylog"
	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"
)

var (
	CleanAll      bool
	UnInstallNode []string
	cleanCmd      = &cobra.Command{
		Use:   "clean",
		Short: "Simplest way to clean your k3s HA cluster",
		Long:  `k3sinstall clean --all`,
		Run: func(cmd *cobra.Command, args []string) {
			y, err := ioutil.ReadFile(ConfigFile)
			if err != nil {
				mylog.Error.Panicf("read config file %s failed %w", ConfigFile, err)
			}
			config := &install.K3sConfig{}
			err = yaml.Unmarshal(y, config)
			if err != nil {
				mylog.Error.Panicf("unmarshal config file failed: %w", err)
			}
			if CleanAll {
				install.UnInstallHookAll(config)
			} else {
				if len(UnInstallNode) == 0 {
					mylog.Error.Panic("err no node arg !!!")
					cmd.Help()
				} else {
					for k := range UnInstallNode {
						ip, port, err := parseIpPort(UnInstallNode[k])
						if err != nil {
							mylog.Error.Panicf("解析ip地址失败 ip: %s port: %d  %s /n", ip, port, err.Error())
						}
						ipaddress := net.ParseIP(ip)
						if ipaddress == nil {
							mylog.Error.Panicf("解析ip地址失败 请确认node参数并指定正确格式的ip地址 ip: %s port %d \n", ip, port)

						}
						if port < 1 || port > 65535 {
							mylog.Error.Panicf("解析ip地址失败 请确认node参数并指定正确格式的ip地址 ip: %s port %d \n", ip, port)
						}
						UnInstallNode[k] = fmt.Sprintf("%s:%d", ipaddress.String(), port)
					}

					install.UnInstallHookNodes(config, UnInstallNode)

				}
			}

		},
		PreRun: func(cmd *cobra.Command, args []string) {
			home, err := Home()
			if err != nil {
				mylog.Error.Panicf("获取Home目录失败 %s", err.Error())
			}
			ConfigHome = home
			if !FileExist(home + "/.k3sinstall") {
				mylog.Error.Panicf("can not find config file , is install k3s cluster ?")

			}
			ConfigFile = home + "/.k3sinstall/config.yaml"
		},
	}
)

func init() {
	cleanCmd.Flags().BoolVar(&CleanAll, "all", false, "clean all k3s nodes")
	cleanCmd.Flags().StringSliceVar(&UnInstallNode, "node", []string{}, "uninstall nodes")
}
